package com.ldc.common.utils;

import com.google.gson.Gson;
import com.ldc.common.constants.ConstantsHttpCreator;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @auther liudc
 * @since 2022/11/5
 */
public class ResponseUtils {
    private final static Gson gson;

    static {
        gson = new Gson();
    }

    /**
     * 放回结果
     *
     * @param response 响应
     * @param data     数据
     * @param <T>      类型
     */
    public static <T> void toResult(HttpServletResponse response, T data) {
        response.setCharacterEncoding(ConstantsHttpCreator.CHARSET_UTF_8);
        response.setContentType(ConstantsHttpCreator.CONTENT_TYPE_JSON);
        PrintWriter printWriter = null;
        try {
            printWriter = response.getWriter();
            printWriter.write(gson.toJson(data));
        } catch (IOException e) {
            //
        } finally {
            if (printWriter != null) {
                printWriter.flush();
                printWriter.close();
            }
        }
    }
}
